import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getCurrentUser } from '../api/user'

export const useUserStore = defineStore('user', () => {
    const token = ref(localStorage.getItem('token') || '')
    const currentUser = ref(null)
    const isLoggedIn = ref(false)

    // 设置 token
    const setToken = (newToken) => {
        if (!newToken) return
        // 确保 token 格式正确
        const tokenValue = newToken.startsWith('Bearer ') ? newToken : `Bearer ${newToken}`
        token.value = tokenValue
        localStorage.setItem('token', tokenValue)
        isLoggedIn.value = true
    }

    // 设置用户信息
    const setUserInfo = (userInfo) => {
        if (!userInfo) return
        currentUser.value = userInfo
        isLoggedIn.value = true
    }

    // 获取当前用户信息
    const fetchCurrentUser = async () => {
        if (!token.value) {
            logout()
            return
        }

        try {
            const res = await getCurrentUser()
            if (res.code === 200 && res.data) {
                currentUser.value = res.data
                isLoggedIn.value = true
            } else {
                throw new Error(res.message || '获取用户信息失败')
            }
        } catch (error) {
            console.error('Fetch current user error:', error)
            logout()
            throw error
        }
    }

    // 退出登录
    const logout = () => {
        token.value = ''
        currentUser.value = null
        isLoggedIn.value = false
        localStorage.removeItem('token')
    }

    return {
        token,
        currentUser,
        isLoggedIn,
        setToken,
        setUserInfo,
        fetchCurrentUser,
        logout
    }
}) 